package com.example.siteservices.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.siteservices.dto.FileFilterRequest;
import com.example.siteservices.dto.FileRequest;
import com.example.siteservices.dto.PhotoFileRequest;
import com.example.siteservices.entity.File;
import com.example.siteservices.mapper.FileMapper;
import com.example.siteservices.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
import org.springframework.web.multipart.MultipartFile;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private FileMapper fileMapper;

    @Value("${file.upload.path}")
    private String uploadPath;

    @Override
    public List<FileRequest> getAllFiles() {
        return fileMapper.selectList(null).stream()
                .map(this::mapToFileRequest)
                .collect(Collectors.toList());
    }

    @Override
    public List<FileRequest> getAllFilesWithFilters(FileFilterRequest fileFilterRequest) {
        // 构建查询条件
        LambdaQueryWrapper<File> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加文件名筛选条件（模糊查询）
        if (StringUtils.isNotBlank(fileFilterRequest.getFileName())) {
            queryWrapper.like(File::getFileName, fileFilterRequest.getFileName());
        }
        
        // 添加文件地址筛选条件
        if (StringUtils.isNotBlank(fileFilterRequest.getFileAdress())) {
            queryWrapper.eq(File::getFileAdress, fileFilterRequest.getFileAdress());
        }
        
        // 添加文件类型筛选条件
        if (StringUtils.isNotBlank(fileFilterRequest.getFileType())) {
            queryWrapper.eq(File::getFileType, fileFilterRequest.getFileType());
        }
        
        // 添加时间范围筛选条件
        if (StringUtils.isNotBlank(fileFilterRequest.getStartDate()) && 
            StringUtils.isNotBlank(fileFilterRequest.getEndDate())) {
            LocalDateTime startDate = LocalDateTime.parse(fileFilterRequest.getStartDate());
            LocalDateTime endDate = LocalDateTime.parse(fileFilterRequest.getEndDate());
            queryWrapper.between(File::getUploadTime, startDate, endDate);
        }

        // 添加排序条件（按上传时间降序）
        queryWrapper.orderByDesc(File::getUploadTime);

        // 创建分页对象
        Page<File> page = new Page<>(
            fileFilterRequest.getCurrent() != null ? fileFilterRequest.getCurrent() : 1,
            fileFilterRequest.getPageSize() != null ? fileFilterRequest.getPageSize() : 10
        );

        // 执行分页查询
        Page<File> filePage = fileMapper.selectPage(page, queryWrapper);

        // 转换结果
        return filePage.getRecords().stream()
                .map(this::mapToFileRequest)
                .collect(Collectors.toList());
    }

    @Override
    public List<FileRequest> getPhotoFilesList(PhotoFileRequest fileRequest){
        // 构建查询条件
        LambdaQueryWrapper<File> queryWrapper = new LambdaQueryWrapper<>();

        // 添加文件名筛选条件（模糊查询）
        if (StringUtils.isNotBlank(fileRequest.getFileName())) {
            queryWrapper.like(File::getFileName, fileRequest.getFileName());
        }

        // 添加文件类型筛选条件
        if (StringUtils.isNotBlank(fileRequest.getFileType())) {
            queryWrapper.like(File::getFileType, fileRequest.getFileType());
        }

        // 创建分页对象
        Page<File> page = new Page<>(
                fileRequest.getCurrent() != null ? fileRequest.getCurrent() : 1,
                fileRequest.getPageSize() != null ? fileRequest.getPageSize() : 10
        );

        // 执行分页查询
        Page<File> filePage = fileMapper.selectPage(page, queryWrapper);

        System.out.println("\n\n"+ filePage.getRecords().stream()
                .map(this::mapToFileRequest)
                .collect(Collectors.toList()) + "\n\n");

        // 转换结果
        return filePage.getRecords().stream()
                .map(this::mapToFileRequest)
                .collect(Collectors.toList());
    }

    @Override
    public FileRequest getFileById(Integer id) {
        File fileEntity = fileMapper.selectById(id);
        if (fileEntity == null) {
            throw new RuntimeException("File not found with id: " + id);
        }
        return mapToFileRequest(fileEntity);
    }

    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        // 检查文件是否为空
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传的文件不能为空");
        }

        // 生成文件存储路径
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + fileExtension;
        
        // 使用Paths来处理路径
        Path uploadDir = Paths.get(uploadPath);
        Path filePath = uploadDir.resolve(fileName);

        // 确保目录存在
        if (!Files.exists(uploadDir)) {
            Files.createDirectories(uploadDir);
        }

        // 保存文件到服务器
        Files.copy(file.getInputStream(), filePath);

        return filePath.toString();
    }

    @Override
    public FileRequest saveFileInfo(FileRequest fileRequest) throws Exception {
        // 创建文件记录
        File fileEntity = new File();
        fileEntity.setFileName(fileRequest.getFileName());
        fileEntity.setFilePath(fileRequest.getFilePath());
        fileEntity.setFileAdress(fileRequest.getFileAdress());
        fileEntity.setFileType(fileRequest.getFileType());
        fileEntity.setUploadName(fileRequest.getUploadName());
        fileEntity.setCreateTime(LocalDateTime.now());
        fileEntity.setUploadTime(LocalDateTime.now());

        // 保存到数据库
        fileMapper.insert(fileEntity);

        // 返回文件信息
        return mapToFileRequest(fileEntity);
    }

    private FileRequest mapToFileRequest(File fileEntity) {
        FileRequest fileResponseDTO = new FileRequest();
        fileResponseDTO.setId(fileEntity.getId());
        fileResponseDTO.setFileName(fileEntity.getFileName());
        fileResponseDTO.setFilePath(fileEntity.getFilePath());
        fileResponseDTO.setFileAdress(fileEntity.getFileAdress());
        fileResponseDTO.setFileType(fileEntity.getFileType());
        fileResponseDTO.setUploadName(fileEntity.getUploadName());
        fileResponseDTO.setCreateTime(fileEntity.getCreateTime().toString());
        fileResponseDTO.setUploadTime(fileEntity.getUploadTime().toString());
        return fileResponseDTO;
    }
}
